# 
# Inspired by 
#   http://dev.rubyonrails.org/svn/rails/plugins/account_location/lib/account_location.rb
# 
module WikiSubdomains
  def self.included( controller )
    controller.helper_method(:wiki_domain, :wiki_subdomain, :wiki_url, :current_wiki, :default_wiki_subdomain, :default_wiki_url)
  end
  
  protected
    
    # TODO: need to handle www as well
    def default_wiki_subdomain
      ''
    end
    
    def wiki_url( wiki_subdomain = default_wiki_subdomain, use_ssl = request.ssl? )
      http_protocol(use_ssl) + wiki_host(wiki_subdomain)
    end
    
    def wiki_host( subdomain )
      wiki_host = ''
      wiki_host << subdomain + '.'
      wiki_host << wiki_domain
    end

    def wiki_domain
      wiki_domain = ''
      wiki_domain << request.domain + request.port_string
    end

    def wiki_subdomain
      request.subdomains.first || ''
    end
    
    def default_wiki_url( use_ssl = request.ssl? )
      default_url = ''
      default_url << http_protocol(use_ssl)
      default_url << default_wiki_subdomain + '.' if !default_wiki_subdomain.empty?
      default_url << wiki_domain
    end      
          
    def current_wiki
      Wiki.find_by_subdomain(wiki_subdomain)
    end
    
    def http_protocol( use_ssl = request.ssl? )
      (use_ssl ? "https://" : "http://")
    end 
end